package nl.boelen.game.server.connection;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import nl.boelen.game.net.packet.Packet;
import nl.boelen.game.options.Option;

public class ServerUDP extends Thread {

    private DatagramSocket socket;
    public boolean hasSocket = false;
    private ServerPacketHandler packetHandler;

    public ServerUDP(ServerPacketHandler packetHandler) {
        this.packetHandler = packetHandler;

        try {
            this.socket = new DatagramSocket(Option.ServerPort);
            this.hasSocket = true;
        } catch (BindException e) {
            this.hasSocket = false;
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            byte[] data = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);
            try {
                socket.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            packetHandler.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
        }
    }

    public void sendPacket(Packet packet, InetAddress ipAddress, int port) {
        DatagramPacket dataPacket = new DatagramPacket(packet.getData(), packet.getData().length, ipAddress, port);
        try {
            socket.send(dataPacket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
